import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { Row, Col, Card, Button, message, Form, Input, Modal, InputNumber, Table, Upload, Icon } from 'antd';
import ClassifyTable from 'components/ClassifyTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import { logo } from '../../components/PageHeader';
import information from '../../utils/message';
import styles from './list.less';
import './classfily.less';
import { imgUrl } from '../../services/setting';

const imgUpdate = `${imgUrl}/v1/platform/common/file/upload/image`;
const ButtonGroup = Button.Group;
const FormItem = Form.Item;
const confirm = Modal.confirm;
function beforeUpload(file) {
    const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJPG) {
        message.error('请上传JPG/PNG格式');
    }
    const isLt2M = file.size / 1024 / 1024 < 5;
    if (!isLt2M) {
        message.error('上传大小限制为5MB');
    }
    return isJPG && isLt2M;
}
const CreateForm = Form.create()((props) => {
    const { modalVisible, form, handleAdd, handleModalVisible, classifyBer, indexUpdate, loadings, pid } = props;
    const uploadButton = (
        <div>
            <Icon type={loadings ? 'loading' : 'plus'} />
            <div className="ant-upload-text">Upload</div>
        </div>
    );
    const okHandle = () => {
        form.validateFields((err, fieldsValue) => {
            if (err) return;
            const prime = fieldsValue;
            if (typeof (fieldsValue.image) !== 'undefined') {
                if (typeof (fieldsValue.image.file.response) !== 'undefined') {
                    prime.image = fieldsValue.image.file.response.data.path;
                } else {
                    delete prime.image;
                }
            }
            form.resetFields();
            handleAdd(prime, classifyBer.id);
        });
    };
    const canaleModal = () => {
        handleModalVisible();
        form.resetFields();
    };
    let { imageUrlBase } = props;
    if (props.imageUrlBase === '') imageUrlBase = classifyBer.image;

    let arrName = [];
    if (pid === 0) {
        arrName = ['编辑主分类', '主分类名', '主分类排序值', '主分类图片'];
    } else {
        arrName = ['编辑子分类', '子分类名', '子分类排序值', '子分类图片'];
    }
    return (
        <Modal
            title={arrName[0]}
            visible={modalVisible}
            onOk={okHandle}
            onCancel={canaleModal}
        >
            <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                <Col md={24} sm={24}>
                    <FormItem
                        labelCol={{ span: 6 }}
                        wrapperCol={{ span: 14 }}
                        label={arrName[1]}
                    >
                        {form.getFieldDecorator('name', {
                            rules: [{ required: true, message: '请输入正确的产品分类名' }],
                            initialValue: classifyBer.name,
                        })(
                            <Input placeholder="请输入" />
                        )}
                    </FormItem>
                    <FormItem
                        labelCol={{ span: 6 }}
                        wrapperCol={{ span: 14 }}
                        label={arrName[2]}
                    >
                        {form.getFieldDecorator('orderNum', {
                            rules: [{ required: true, message: '请输入正确的产品分类排序值(不支持负数)' }],
                            initialValue: classifyBer.orderNum,
                        })(
                            <InputNumber min={0} />
                        )}
                    </FormItem>
                    <FormItem
                        labelCol={{ span: 6 }}
                        wrapperCol={{ span: 14 }}
                        label={arrName[3]}
                    >
                        {form.getFieldDecorator('image')(
                            <Upload
                                name="file"
                                listType="picture-card"
                                className="avatar-uploader"
                                showUploadList={false}
                                action={imgUpdate}
                                headers={{ Authorization: sessionStorage.getItem('token') }}
                                beforeUpload={beforeUpload}
                                onChange={indexUpdate}
                            >
                                {imageUrlBase ? <img src={imageUrlBase} alt="" style={{ width: '100%' }} /> : uploadButton}
                            </Upload>
                        )}
                    </FormItem>
                </Col>
            </Row>
        </Modal>
    );
});

const NewForm = Form.create()((props) => {
    const { modalVisible, form, handleAdd, handleModalVisible, indexUpdate, loadings, pid, imageUrlBase } = props;
    const uploadButton = (
        <div>
            <Icon type={loadings ? 'loading' : 'plus'} />
            <div className="ant-upload-text">Upload</div>
        </div>
    );
    const okHandle = () => {
        form.validateFields((err, fieldsValue) => {
            if (err) return;
            const prime = fieldsValue;
            if (typeof (fieldsValue.image) !== 'undefined') {
                if (typeof (fieldsValue.image.file.response) !== 'undefined') {
                    prime.image = fieldsValue.image.file.response.data.path;
                } else {
                    delete prime.image;
                }
            }
            form.resetFields();
            handleAdd(prime, pid);
        });
    };
    const canaleModal = () => {
        handleModalVisible();
        form.resetFields();
    };
    let arrName = [];
    if (pid === 0) {
        arrName = ['新增主分类', '主分类名', '主分类排序值', '主分类图片'];
    } else {
        arrName = ['新增子分类', '子分类名', '子分类排序值', '子分类图片'];
    }
    return (
        <Modal
            title={arrName[0]}
            visible={modalVisible}
            onOk={okHandle}
            onCancel={canaleModal}
        >
            <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                <Col md={24} sm={24}>
                    <FormItem
                        labelCol={{ span: 6 }}
                        wrapperCol={{ span: 14 }}
                        label={arrName[1]}
                    >
                        {form.getFieldDecorator('name', {
                            rules: [{ required: true, message: '请输入正确的产品分类名' }],
                        })(
                            <Input placeholder="请输入" />
                        )}
                    </FormItem>
                    <FormItem
                        labelCol={{ span: 6 }}
                        wrapperCol={{ span: 14 }}
                        label={arrName[2]}
                    >
                        {form.getFieldDecorator('orderNum', {
                            rules: [{ required: true, message: '请输入正确的产品分类排序值(不支持负数)' }],
                        })(
                            <InputNumber min={0} />
                        )}
                    </FormItem>
                    <FormItem
                        labelCol={{ span: 6 }}
                        wrapperCol={{ span: 14 }}
                        label={arrName[3]}
                    >
                        {form.getFieldDecorator('image')(
                            <Upload
                                name="file"
                                listType="picture-card"
                                className="avatar-uploader"
                                showUploadList={false}
                                action={imgUpdate}
                                beforeUpload={beforeUpload}
                                headers={{ Authorization: sessionStorage.getItem('token') }}
                                onChange={indexUpdate}
                            >
                                {imageUrlBase ? <img src={imageUrlBase} alt="" style={{ width: '100%' }} /> : uploadButton}
                            </Upload>
                        )}
                    </FormItem>
                </Col>
            </Row>
        </Modal>
    );
});

@connect(({ classify, loading }) => ({
    classify,
    loading: loading.models.classify,
}))
@Form.create()
export default class classify extends PureComponent {
    state = {
        loadings: false,
        selectedRows: [],
        modalVisible: false,
        modalVisibleAdd: false,
        classifyBer: {},
        imageUrlBase: '',
        pid: 0,
        searchForm: {},
    };

    componentDidMount() {
        this.gainList(1, 100);
    }

    gainList = (page, size, data) => {
        const { dispatch } = this.props;
        dispatch({
            type: 'classify/fetch',
            payload: {
                page,
                size,
                data,
            },
        });
    }

    handleModalVisible = (flag) => {
        this.setState({
            modalVisible: !!flag,
        });
    };

    classifyAdd = (flag) => {
        this.setState({
            modalVisibleAdd: !!flag,
            imageUrlBase: '',
        });
    };

    handleEdit = (fields, id) => {
        const parime = fields;
        const { dispatch } = this.props;
        dispatch({
            type: 'classify/edit',
            payload: {
                ...parime,
                id,
            },
            callback: (data) => {
                information(data);
                this.gainList(this.props.classify.classify.page, this.props.classify.classify.size, this.state.searchForm);
            },
        });
        this.setState({
            modalVisible: false,
        });
    };

    handleAdd = (fields, pid) => {
        const parime = fields;
        if (typeof (parime.image) === 'undefined') {
            message.error('请上传图片');
            return;
        }
        const { dispatch } = this.props;
        dispatch({
            type: 'classify/add',
            payload: {
                ...parime,
                pid,
            },
            callback: (data) => {
                information(data);
                this.gainList(this.props.classify.classify.page, this.props.classify.classify.size, this.state.searchForm);
            },
        });
        this.setState({
            modalVisibleAdd: false,
        });
    };

    classifyDel = (fields) => {
        const { dispatch, classify: { classify } } = this.props;
        confirm({
            title: '删除',
            content: '确认删除本条条目?',
            okType: 'danger',
            okText: '确认',
            cancelText: '取消',
            onOk: () => {
                dispatch({
                    type: 'classify/del',
                    payload: {
                        id: fields.id,
                    },
                    callback: (data) => {
                        information(data);
                        this.gainList(classify.page, classify.size, this.state.searchForm);
                    },
                });
            },
            onCancel() {
            },
        });
    }

    handleSelectRows = (rows) => {
        this.setState({
            selectedRows: rows,
        });
    };

    handleClassifyTableChange = (pagination, filters, sorter) => {
        const data = { ...pagination.searchForm };
        const { dispatch } = this.props;
        const params = {
            page: pagination.current,
            size: pagination.pageSize,
            data,
        };
        dispatch({
            type: 'classify/fetch',
            payload: params,
        });
    };

    handleFormReset = () => {
        const { form, dispatch } = this.props;
        form.resetFields();
        this.setState({ searchForm: {} });
    };

    handleSearch = (e) => {
        e.preventDefault();

        const { dispatch, form } = this.props;

        form.validateFields((err, fieldsValue) => {
            if (err) return;
            if (fieldsValue.id && fieldsValue.id.toString().length > 10) {
                message.error('id小于等于10位');
                return;
            }
            this.setState({
                searchForm: { ...fieldsValue },
            });
            dispatch({
                type: 'classify/fetch',
                payload: {
                    page: 1,
                    size: this.props.classify.classify.size,
                    data: {
                        ...fieldsValue,
                    },
                },
                callback: (data) => {
                    information(data);
                },
            });
        });
    };

    expandedRowRender = (data) => {
        const columns = [
            {
                title: 'id',
                width: '112px',
                dataIndex: 'id',
            },
            {
                title: 'image',
                width: '200px',
                dataIndex: 'image',
                render: (val) => {
                    return val ? <img src={val} alt="" style={{ height: '50px' }} /> : '暂无图片';
                },
            },
            {
                title: 'name',
                dataIndex: 'name',
                width: '21.5%',
            },
            {
                title: 'orderNum',
                width: '100px',
                dataIndex: 'orderNum',
            },
            {
                title: 'Action',
                dataIndex: 'operation',
                render: (val, record) => (
                    <ButtonGroup size="small">
                        <Button type="ghost" onClick={() => {
                            this.handleModalVisible(true);
                            this.setState({
                                classifyBer: record,
                                pid: -1,
                                imageUrlBase: '',
                            });
                        }}>编辑</Button>
                        <Button type="danger" onClick={() => this.classifyDel(record)}>删除</Button>
                    </ButtonGroup>
                ),
            },
        ];
        return (
            <Table
                columns={columns}
                rowKey={record => record.id}
                dataSource={data.childrenList}
                pagination={false}
                locale={{ emptyText: '暂无子分类' }}
                showHeader={false}
            />
        );
    };

    indexUpdate = ({ fileList, file }) => {
        const { status, response } = file;
        const { dispatch } = this.props;
        if (file.response && file.response.code !== 20000) {
            message.error(`${file.response.message},请重新登录`);
            dispatch({ type: 'login/logout' });
        }
        if (status === 'uploading') {
            this.setState({ loading: true });
            return;
        }
        if (status === 'done') {
            this.setState({
                loading: false,
                imageUrlBase: response.data.pathFull,
            });
        }
    };

    renderclassifyForm() {
        const { getFieldDecorator } = this.props.form;
        return (
            <Form onSubmit={this.handleSearch} layout="inline">
                <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                    <Col md={6} sm={24}>
                        <FormItem label="分类ID">
                            {getFieldDecorator('id', {
                                initialValue: '',
                            })(
                                <InputNumber style={{ width: '100%' }} min={1} max={2147483647} placeholder="请输入" />
                            )}
                        </FormItem>
                    </Col>
                    <Col md={6} sm={24}>
                        <FormItem label="分类名字">
                            {getFieldDecorator('name', {
                                initialValue: '',
                            })(
                                <Input placeholder="请输入" />
                            )}
                        </FormItem>
                    </Col>

                    <Col md={6} sm={24}>
                        <span className={styles.submitButtons} style={{ textAlign: 'right' }}>
                            <Button icon="search" htmlType="submit">查询</Button>
                            <Button style={{ marginLeft: 8 }} type="dashed" onClick={this.handleFormReset}>重置</Button>
                            <Button style={{ marginLeft: 8 }} type="primary" onClick={this.classifyAdd}>新增主分类</Button>
                        </span>
                    </Col>
                </Row>
            </Form>
        );
    }


    render() {
        const { selectedRows, classifyBer, modalVisible, modalVisibleAdd, loadings, imageUrlBase, pid } = this.state;
        const { classify: { classify }, loading, dispatch } = this.props;
        const parentMethods = {
            handleAdd: this.handleEdit,
            handleModalVisible: this.handleModalVisible,
            indexUpdate: this.indexUpdate,
            classifyBer,
            loading,
            loadings,
            imageUrlBase,
            pid,
        };
        const Addclassify = {
            loading,
            handleAdd: this.handleAdd,
            handleModalVisible: this.classifyAdd,
            indexUpdate: this.indexUpdate,
            loadings,
            imageUrlBase,
            pid,
        };
        const columns = [
            {
                title: 'ID',
                dataIndex: 'id',
                width: '120px',
            },
            {
                title: '分类图片',
                width: '200px',
                dataIndex: 'image',
                render: (val) => {
                    return val ? <img src={val} alt="" style={{ height: '50px' }} /> : '暂无图片';
                },
            },
            {
                title: '分类名称',
                dataIndex: 'name',
                width: '20%',
            },
            {
                title: '排序值',
                width: '100px',
                dataIndex: 'orderNum',
            },
            {
                title: '操作',
                render: (val, record) => {
                    return (
                        <Fragment>
                            <ButtonGroup>
                                <Button type="primary" onClick={(e) => {
                                    e.stopPropagation();
                                    this.setState({
                                        modalVisibleAdd: true,
                                        pid: val.id,
                                        imageUrlBase: '',
                                    });
                                }}>新增子分类</Button>
                                <Button type="ghost" onClick={(e) => {
                                    e.stopPropagation();
                                    this.handleModalVisible(true);
                                    this.setState({
                                        classifyBer: record,
                                        pid: 0,
                                        imageUrlBase: '',
                                    });
                                }}>编辑</Button>
                                <Button type="danger" onClick={(e) => {
                                    e.stopPropagation();
                                    this.classifyDel(record);
                                }}>删除</Button>
                            </ButtonGroup>
                        </Fragment>
                    );
                },
            },
        ];
        return (
            <PageHeaderLayout title="分类列表">
                <Card bordered={false}>
                    <div className={styles.tableList}>
                        <div className={styles.tableListForm}>
                            {this.renderclassifyForm()}
                        </div>
                        <ClassifyTable
                            selectedRows={selectedRows}
                            loading={loading}
                            data={classify}
                            columns={columns}
                            expandedRowRender={this.expandedRowRender}
                            onChange={this.handleClassifyTableChange}
                            searchForm={this.state.searchForm}
                        />
                    </div>
                </Card>
                <CreateForm
                    {...parentMethods}
                    modalVisible={modalVisible}
                />
                <NewForm
                    {...Addclassify}
                    modalVisible={modalVisibleAdd}
                />
            </PageHeaderLayout>
        );
    }
}
